package com.snail.controller;

import com.snail.model.vo.UserVo;
import com.snail.service.AiContentService;
import com.snail.service.BizMediaDocService;
import com.snail.service.BizMediaFileService;
import com.snail.service.impl.BizMediaFileServiceImpl;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/video")
public class VideoController {


    private static final Logger log = LoggerFactory.getLogger(VideoController.class);

    @Value("${minio.endpoint}")
    private String endPoint;

    @Resource
    private BizMediaFileService bizMediaFileService;

    @Resource
    private BizMediaFileServiceImpl bizMediaFileServiceImpl;

    @Resource
    private BizMediaDocService bizMediaDocService;

    @Resource
    private AiContentService aiContentService;

    /**
     * 生成新的总结视频
     * @param payload
     * @return
     * @throws IOException
     */
    @PostMapping("/summarize")
    public ResponseEntity<Map<String, Object>> summarizeVideo(@RequestBody Map<String, String> payload) throws IOException {
        Map<String, Object> response = new HashMap<>();
        Integer videoId = Integer.parseInt(payload.get("videoId"));
        Integer userId = Integer.parseInt(payload.get("userId"));
        Integer outlineId = Integer.parseInt(payload.get("outlineId"));
        String summaryText = null;
        Integer subtitleId;
        String subtitleText;
        try {
            // 先拿字幕文件
            if ((subtitleId = bizMediaFileService.getSubtitleId(videoId)) != 0) {
                System.out.println("subtitleId--------" + subtitleId);
                subtitleText = bizMediaDocService.getContentById(subtitleId);
                log.info("已拿到字幕文件\n" + subtitleText);
            } else {
                // 获取Url
//                String videoUrl = bizMediaFileServiceImpl.minioEndpoint + "/video/" + bizMediaFileService.getById(videoId).getFilePath();
                String videoUrl = endPoint + "/video/" + bizMediaFileService.getById(videoId).getFilePath();
                System.out.println("===============" + videoUrl);
                Path tempVideoFile = bizMediaFileService.downloadVideoFile(videoUrl);
                File videoFile = tempVideoFile.toFile();
                // 定义输出音频文件路径
                File audioFile = new File(Paths.get(bizMediaFileServiceImpl.TEMP_DIR).toAbsolutePath() + "/output.wav");
                bizMediaFileService.convertVideoToAudio(videoFile, audioFile);
                // 2. 音频转文字srt格式
                subtitleText = bizMediaFileService.transcribeAudioToString(audioFile);
                log.warn("123123123-------------" + subtitleText);
            }

            // 3. 文字转总结文档
            String sysPropmt = "请根据提供的 SRT 字幕文件内容，生成一份 Markdown 格式的总结文档。要求如下：\n\n内容划分：将视频内容划分" +
                    "为若干个逻辑清晰的主题或章节。\n关键要点：在每个主题下提取核心知识点、技巧、建议或操作方法。\n时间节点标注：为每个关键要" +
                    "点添加其在视频中出现的时间戳（格式如：@00:00:04），紧随要点之后。\n格式规范：\n使用 Markdown 的标题（#, ##, ###）进" +
                    "行结构划分。\n使用列表项（- 或 *）列出每个要点。\n时间戳只写在大的标题几点后\n不使用任何 HTML 标签或复杂排版。\n语言风" +
                    "格：详实准确\n忠于原始 SRT 内容，但也可以适当扩展。\n可对技术术语保持原样引用。";
            summaryText = aiContentService.generateAiContentAndSave(sysPropmt, subtitleText, videoId, userId, outlineId);
            System.out.println("-------------" + summaryText + "总结文档已保存至用户" + userId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除临时文件
            Files.list(Paths.get(bizMediaFileServiceImpl.TEMP_DIR))
                    .filter(Files::isRegularFile)
                    .forEach(path -> {
                        try {
                            Files.delete(path);
                        } catch (IOException e) {
                            System.err.println("删除失败: " + path);
                        }
                    });
        }
        response.put("success", true);
        response.put("data", summaryText);
        return ResponseEntity.accepted().body(response);
    }

    /**
     * 获取总结文档
     */
    @PostMapping("/getSummary")
    public ResponseEntity<Map<String, Object>> getSummary(@RequestBody Map<String, String> payload) {
        Map<String, Object> response = new HashMap<>();
        Integer videoId = Integer.parseInt(payload.get("videoId"));
        Integer userId = Integer.parseInt(payload.get("userId"));
        Integer outlineId = Integer.parseInt(payload.get("outlineId"));
        if (bizMediaDocService.getDocByUserIdAndOutlineId(new UserVo(userId, videoId, outlineId)) == null) {
            response.put("success", true);
            response.put("data", "");
            return ResponseEntity.accepted().body(response);
        }
        String summaryText = bizMediaDocService.getDocByUserIdAndOutlineId(new UserVo(userId, videoId, outlineId)).getContent();
        response.put("success", true);
        response.put("data", summaryText);
        return ResponseEntity.accepted().body(response);
    }
}